package 基础篇.线程池.ForkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created by Administrator on 2018/7/29 0029.
 */
public class CalTask extends RecursiveTask<Integer>{
    private static final int THRESHOLD=50;
    private int start;
    private int end;
    public CalTask(int start,int end){
        this.start=start;
        this.end=end;
    }
    @Override
    protected Integer compute() {
        if(end-start<THRESHOLD){
            int sum=0;
            for(int i=start;i<end;i++){
                sum+=i;
            }
            System.out.println("sum:"+sum);
            return sum;
        }else {
            int middle=(start+end)/2;
            CalTask left=new CalTask(start,middle);
            CalTask right=new CalTask(middle,end);
            //并行执行两个人物
            left.fork();
            right.fork();
            return left.join()+right.join();
        }
    }
}

 class RecursiveTaskDemo{
     public static void main(String[] args) throws ExecutionException, InterruptedException {
         ForkJoinPool pool=ForkJoinPool.commonPool();
         RecursiveTask task=new CalTask(0,100);
         Future<Integer> future=pool.submit(task);
         System.out.println(future.get());
         pool.shutdown();
     }
 }
